package com.ruoyi.web.service.impl;

import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.mapper.TbAddressMapper;
import com.ruoyi.web.domain.TbAddress;
import com.ruoyi.web.service.ITbAddressService;

/**
 * 用户地址溥Service业务层处理
 *
 * @author cacode
 * @date 2024-03-19
 */
@Service
public class TbAddressServiceImpl implements ITbAddressService {
    @Autowired
    private TbAddressMapper tbAddressMapper;

    /**
     * 查询用户地址溥
     *
     * @param id 用户地址溥主键
     * @return 用户地址溥
     */
    @Override
    public TbAddress selectTbAddressById(Long id) {
        return tbAddressMapper.selectTbAddressById(id);
    }

    /**
     * 查询用户地址溥列表
     *
     * @param tbAddress 用户地址溥
     * @return 用户地址溥
     */
    @Override
    public List<TbAddress> selectTbAddressList(TbAddress tbAddress) {
        return tbAddressMapper.selectTbAddressList(tbAddress);
    }

    /**
     * 新增用户地址溥
     *
     * @param tbAddress 用户地址溥
     * @return 结果
     */
    @Override
    public int insertTbAddress(TbAddress tbAddress) {
        if(tbAddress.getIsDefault()){
            tbAddressMapper.resetDefault(tbAddress.getUserId());
        }
        return tbAddressMapper.insertTbAddress(tbAddress);
    }

    /**
     * 修改用户地址溥
     *
     * @param tbAddress 用户地址溥
     * @return 结果
     */
    @Override
    public int updateTbAddress(TbAddress tbAddress) {
        if(tbAddress.getIsDefault()){
            tbAddressMapper.resetDefault(tbAddress.getUserId());
        }
        return tbAddressMapper.updateTbAddress(tbAddress);
    }

    /**
     * 批量删除用户地址溥
     *
     * @param ids 需要删除的用户地址溥主键
     * @return 结果
     */
    @Override
    public int deleteTbAddressByIds(Long[] ids) {
        return tbAddressMapper.deleteTbAddressByIds(ids);
    }

    /**
     * 删除用户地址溥信息
     *
     * @param id 用户地址溥主键
     * @return 结果
     */
    @Override
    public int deleteTbAddressById(Long id) {
        return tbAddressMapper.deleteTbAddressById(id);
    }

    /**
     * 修改默认地址
     * @param userId
     * @param id
     * @return
     */
    @Override
    public int updateDef(Long userId,Long id) {
        // 重置所有默认地址
        boolean resetDefault = tbAddressMapper.resetDefault(userId);
        if(!resetDefault){
            throw new ServiceException("更新默认地址失败");
        }
        int i = updateTbAddress(new TbAddress().setId(id).setIsDefault(true));
        //设置指定默认地址
        return i;
    }

    @Override
    public TbAddress selectDef(Long userId) {
        return tbAddressMapper.selectDef(userId);
    }
}
